package com.onelap.bls.treadmillcalibration.activity.entry;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.bls.blslib.base.BaseActivity;
import com.bls.blslib.eventbus.Event;
import com.bls.blslib.eventbus.EventBusUtils;
import com.google.gson.Gson;
import com.onelap.bls.treadmillcalibration.R;

import com.onelap.bls.treadmillcalibration.activity.calibration.CalibrationActivity;
import com.onelap.bls.treadmillcalibration.activity.index.DeviceBean;
import com.onelap.bls.treadmillcalibration.service.UartService;
import com.onelap.bls.treadmillcalibration.utils.BLeUtil;
import com.onelap.bls.treadmillcalibration.utils.TitleBar;

import java.io.UnsupportedEncodingException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.onelap.bls.treadmillcalibration.utils.BLeUtil.Params.ACTION_DATA_AVAILABLE;
import static com.onelap.bls.treadmillcalibration.utils.BLeUtil.Params.ACTION_GATT_CONNECTED;
import static com.onelap.bls.treadmillcalibration.utils.BLeUtil.Params.ACTION_GATT_DISCONNECTED;
import static com.onelap.bls.treadmillcalibration.utils.BLeUtil.Params.ACTION_GATT_SERVICES_DISCOVERED;
import static com.onelap.bls.treadmillcalibration.utils.BLeUtil.Params.DEVICE_DOES_NOT_SUPPORT_UART;
import static com.onelap.bls.treadmillcalibration.utils.BLeUtil.Params.EXTRA_BATTERY_LEVEL;
import static com.onelap.bls.treadmillcalibration.utils.BLeUtil.Params.EXTRA_DATA;

public class EntryActivity extends BaseActivity implements BLeUtil.BleUtilCallback {

    @BindView(R.id.tv_id)
    TextView tvId;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.tv_electric)
    TextView tvElectric;
    @BindView(R.id.btn_wheel_diameters)
    Button btnWheelDiameters;
    @BindView(R.id.btn_slope)
    Button btnSlope;
    @BindView(R.id.btn_switch_to_ble)
    Button btnSwitchToBle;
    // private BluetoothDevice bluetoothDevice;
    private DeviceBean deviceBean;
    private UartService bluetoothLeService;
    private BLeUtil bLeUtil;
    private ProgressDialog progressDialog;


    @Override
    protected void initParams() {
        super.initParams();
        bLeUtil = new BLeUtil(this);
        /*BluetoothDevice intentBluetoothDevice = new Gson().fromJson(getIntent().getStringExtra("Device"), BluetoothDevice.class);
        bluetoothDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(intentBluetoothDevice.getAddress());*/
        deviceBean = new Gson().fromJson(getIntent().getStringExtra("DeviceBean"), DeviceBean.class);
        bLeUtil.bindBleService(getActivity(), UartService.class,
                ACTION_GATT_CONNECTED,
                ACTION_GATT_DISCONNECTED,
                ACTION_GATT_SERVICES_DISCOVERED,
                ACTION_DATA_AVAILABLE,
                EXTRA_BATTERY_LEVEL,
                DEVICE_DOES_NOT_SUPPORT_UART);
    }

    @Override
    protected int initLayoutId() {
        return R.layout.activity_entry;
    }

    @Override
    protected void initFvb() {
        super.initFvb();
        ButterKnife.bind(this);
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        TitleBar titleBar = findViewById(R.id.tb_title_bar);
        titleBar.setTitle("校准选择");
        titleBar.setBackgroundColor(Color.BLACK);
        titleBar.setTitleColor(Color.WHITE);
        titleBar.setLeftImageResource(R.mipmap.a2);
        titleBar.setLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
    }

    @Override
    protected void initView() {
        super.initView();
        tvId.setText("设备ID：".concat(deviceBean.getDevice().getName()));

        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("连接中，请稍等......");
        progressDialog.setCancelable(false);
        progressDialog.show();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                progressDialog.cancel();
            }
        }, 1000);
    }

    @OnClick(R.id.btn_wheel_diameters)
    public void onBtnWheelDiametersClicked() {
        Intent intent = new Intent();
        intent.putExtra("CalibrationType", "ONE");
        intent.putExtra("DeviceBean", new Gson().toJson(deviceBean));
        intent.setClass(getActivity(), CalibrationActivity.class);
        getActivity().startActivity(intent);
    }

    @OnClick(R.id.btn_slope)
    public void onBtnSlopeClicked() {
        Intent intent = new Intent();
        intent.putExtra("CalibrationType", "TWO");
        intent.putExtra("DeviceBean", new Gson().toJson(deviceBean));
        intent.setClass(getActivity(), CalibrationActivity.class);
        getActivity().startActivity(intent);
    }

    @OnClick(R.id.btn_switch_to_ble)
    public void onBtnSwitchToBleClicked() {
        new MaterialDialog.Builder(this).title("提示：").content("切换至蓝牙模式后将无法再次连接，确认切换么？")
                .positiveText("确定").negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                        try {
                            bluetoothLeService.writeRXCharacteristicUTF_8("FFFF");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        EventBusUtils.sendStickyEvent(new Event(0));
                        getActivity().finish();
                    }
                })
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                }).show();

    }

    @Override
    public void onBleUtilCallback(int status, BluetoothDevice device, int rssi, byte[] scanRecord, IBinder rawBinder, Intent intent) {
        switch (status) {
            case BLeUtil.STATUS_SERVICE_CONNECTED:
                bluetoothLeService = ((UartService.LocalBinder) rawBinder).getService();
                LogUtils.i("onServiceConnected mService=", bluetoothLeService);
                if (!bluetoothLeService.initialize()) {
                    LogUtils.i("onServiceConnected mService=", "Unable to initialize Bluetooth");
                    AppUtils.exitApp();
                }
                bluetoothLeService.connect(deviceBean.getDevice().getAddress());
                break;
            case BLeUtil.STATUS_SERVICE_DISCONNECTED:
                bluetoothLeService = null;
                break;
            case BLeUtil.STATUS_ACTION_GATT_SERVICES_DISCOVERED:
                break;
            case BLeUtil.STATUS_ACTION_DATA_AVAILABLE:
                byte[] txValue = intent.getByteArrayExtra(EXTRA_DATA);
                String text = null;
                try {
                    text = new String(txValue, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                LogUtils.i("ReceiveData", text);
        }
    }

    @Override
    protected void initOnDestroy() {
        super.initOnDestroy();
//        bLeUtil.unBindBleService(getActivity());
//        bluetoothLeService.stopSelf();
//        bluetoothLeService = null;
    }
}
